package demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author lingkang
 * Created by 2024/3/26
 */
public class Demo02 {

    public static void main(String[] args) throws IOException, InterruptedException {
        int proxyPort = 9595; // 代理服务器端口
        ServerSocket serverSocket = new ServerSocket(proxyPort);

        while (true) {
            Socket clientSocket = serverSocket.accept(); // 接受客户端连接
            new Thread(() -> {
                try {
                    // 连接到目标服务器
                    Socket targetSocket = new Socket("www.baidu.com", 80); // 替换为实际目标服务器地址和端口

                    // 从客户端读取请求
                    InputStream clientInput = clientSocket.getInputStream();
                    OutputStream serverOutput = targetSocket.getOutputStream();
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = clientInput.read(buffer)) != -1) {
                        serverOutput.write(buffer, 0, bytesRead);
                    }

                    // 从目标服务器读取响应
                    InputStream serverInput = targetSocket.getInputStream();
                    OutputStream clientOutput = clientSocket.getOutputStream();
                    while ((bytesRead = serverInput.read(buffer)) != -1) {
                        clientOutput.write(buffer, 0, bytesRead);
                    }

                    // 关闭连接
                    clientSocket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
